#include "stdafx.h"
#include "YProactorTokenOnRecv.h"
#include "ITcpSession.h"
#include "ITcpSessionCallback.h"
#include <YSimpleSystem/YSimpleSystem.h>
#include <assert.h>

namespace ysimple_network
{
	YProactorTokenOnRecv::YProactorTokenOnRecv(void)
		: m_pCallback(nullptr)
		, m_pSession(nullptr)
	{
	}


	YProactorTokenOnRecv::~YProactorTokenOnRecv(void)
	{
	}

	void YProactorTokenOnRecv::beginInit( IRecvCallback& callback, ITCPSession& session )
	{
		resetOverlapped();

		m_pCallback = &callback;
		m_wsabuf.buf = m_buf;
		m_wsabuf.len = sizeof(m_buf);
		m_pSession = &session;
		m_pSession->addRef();
	}

	bool YProactorTokenOnRecv::onCompleted( bool completionStatus, LONG_PTR completionKey, DWORD dwBytesTransfered )
	{		
		if (completionStatus == false || dwBytesTransfered == 0)
		{
			m_pSession->disconnect();
		}
		else
		{
			m_pCallback->onRecved(*m_pSession, completionStatus, m_buf, dwBytesTransfered);
			//m_pSession->recv(*m_pCallback);
		}
		m_pSession->release();
		return true;
	}

	WSABUF& YProactorTokenOnRecv::getWSABuf()
	{
		return m_wsabuf;
	}

	DWORD YProactorTokenOnRecv::getWSABufCount()
	{
		return 1;
	}

	void YProactorTokenOnRecv::endInit( bool success )
	{
		if (success == false)
		{
			m_pSession->release();
		}
	}

}

